<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="title" @ok="handleSubmit" width="600px" destroyOnClose>
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from "vue"
  import { BasicModal, useModalInner } from "/@/components/Modal"
  import { BasicForm, useForm } from "/@/components/Form/index"
  import { materialGroupFormSchema } from "../material.data"
  import { listDataGroupTree } from "/@/api/infra/dataGroup.ts"
  import { DataGroupBizType } from "/@/components/BizDataGroup/index"
  import { saveOrUpdateGroup } from "/@/api/infra/material"
  import { useMessage } from "/@/hooks/web/useMessage"

  const { createMessage } = useMessage()
  // 声明Emits
  const emit = defineEmits(["register", "success"])
  const isUpdate = ref(true)
  const materialType = ref("")
  //表单配置
  const [registerForm, { resetFields, setFieldsValue, validate, updateSchema }] = useForm({
    schemas: materialGroupFormSchema,
    showActionButtonGroup: false,
    wrapperCol: { lg: 24, md: 24 },
  })
  //表单赋值
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    materialType.value = data.materialType
    //重置表单
    await resetFields()
    setModalProps({ confirmLoading: false, draggable: false, canFullscreen: false })
    isUpdate.value = !!data?.isUpdate
    //表单赋值
    await setFieldsValue({ ...data.record })
    //获取下拉树信息
    const treeData = await listDataGroupTree({ bizType: DataGroupBizType.MATERIAL, groupType: materialType.value })
    updateSchema([
      {
        field: "parentId",
        componentProps: ({ formModel, formActionType }) => {
          const parentId = formModel["parentId"]
          formModel["parentId"] = parentId === "0" || !parentId ? undefined : parentId
          return {
            treeData,
            fieldNames: {
              title: "name",
              key: "id",
              value: "id",
            },
            dropdownStyle: {
              maxHeight: "60vh",
            },
            showSearch: true,
            allowClear: true,
            getPopupContainer: (node) => node.parentNode,
          }
        },
      },
    ])
  })

  //设置标题
  const title = computed(() => (!unref(isUpdate) ? "新增" : "编辑"))
  //表单提交事件
  async function handleSubmit(v) {
    try {
      let values = await validate()
      setModalProps({ confirmLoading: true })
      await saveOrUpdateGroup({ ...values, groupType: materialType.value }, isUpdate.value)
      //关闭弹窗
      closeModal()
      //刷新列表
      emit("success")
      createMessage.success(`${title.value}分组成功`)
    } finally {
      setModalProps({ confirmLoading: false })
    }
  }
</script>
